package xx.services;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import xx.services.util.Constants;

@Path(Constants.RESTFUL_ROOT_PATH + "/gzip")
public class TestGzjs
{
    private static final String ENCODING = "UTF-8";

    @GET
    public String get(@Context
    HttpServletResponse response)
    {
        try
        {
            // response.getWriter().write("我是一个中国人！");
            // if(true)return;
            // File f = new
            // File("E:/workspace/xx.framework2.0/src-web/management/javascripts/jquery-1.4.4.js");
            File f = new File("E:/json.txt");
            InputStream is = new FileInputStream(f);

            StringBuffer buffer = new StringBuffer();
            String line; // 用来保存每行读取的内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "gbk"));
            line = reader.readLine(); // 读取第一行
            while (line != null)
            { // 如果 line 为空说明读完了
                buffer.append(line); // 将读到的内容添加到 buffer 中
                buffer.append("\n"); // 添加换行符
                line = reader.readLine(); // 读取下一行
            }

            byte[] data = buffer.toString().getBytes(ENCODING);
            byte[] output = compress(data);
            // 设置Content-Encoding，这是关键点！
            response.setHeader("Content-Encoding", "gzip");
            // 设置字符集
            response.setCharacterEncoding(ENCODING);
            // 设定输出流中内容长度
            response.setContentLength(output.length);
            OutputStream out = response.getOutputStream();
            out.write(output);
            out.flush();
            out.write(output);
            out.flush();
            out.close();
            return "我是一个中国人！";
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    /**
     * 压缩
     * 
     * @param data
     * @return
     * @throws Exception
     */
    private byte[] compress(byte[] data) throws Exception
    {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 压缩
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        gos.write(data, 0, data.length);
        gos.finish();
        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        return output;
    }
}
